<template>
	<view class="mes-box">
		<!-- 消息展示区域 -->
		<view ref="messagesContainer" class="messages-container">
		  <view v-for="(message, index) in messages" :key="index" class="message-item" :class="{ 'self-message': message.isSelf }">
			<img :src="message.avatar" alt="Avatar" class="avatar">
			<view class="message-content">
			  <view class="user-info" :class="{ 'self-user-info': message.isSelf }">
				<span class="nickname">{{ message.nickName }}</span>
				<span class="level">Lv.{{ message.level }}</span>
				<!-- 替换为性别图片 -->
				<img :src="getGenderImage(message.gender)" alt="Gender" class="gender-image">
			  </view>
			  <view class="chat-bubble">
				{{ message.content }}
			  </view>
			</view>
		  </view>
		</view>
		<!-- 消息输入框和发送按钮 -->
		<view class="input-container">
		  <input v-model="newMessage" placeholder="输入消息" class="message-input" @keydown.enter="sendMessage" ref="input"/>
		  <view @click="sendMessage" class="send-button">发送</view>
		</view>
  </view>
</template>
<script>
export default {
  name: "WorldChatBox",
  data() {
    return {
      messages: [],
      newMessage: "",
      clientObj: client,
      scrollThreshold: 150 // 滚动阈值，距离底部50px内视为需要自动滚动
    };
  },
  mounted() {
    this.initSocket();
  },
  methods: {
	focusInput() {
		uni.createSelectorQuery().in(this).select('.message-input').node().exec((res) => {
			const inputRef = res[0]?.node;
			if (inputRef) {
				 inputRef.focus();
			}
		});
	},
    initSocket() {
      console.log("初始化成功");
      // 订阅消息
      this.clientObj.subscribe("/game/chat", (msg) => {
        console.log("收到消息", msg);
        let data = JSON.parse(msg.body);
        let userInfo = uni.getStorageSync("userChatInfo");
        data.isSelf = userInfo.userId === data.userId;
        this.messages.push(data);
        // 消息更新后执行滚动逻辑
        this.$nextTick(() => this.scrollToBottomIfNeeded());
      });
    },
    sendMessage() {
      if (this.newMessage.trim()) {
        let userInfo = uni.getStorageSync("userChatInfo");
        let json = {
          id: userInfo.userId,
          avatar: userInfo.avatar,
          nickName: userInfo.nickName,
          level: userInfo.level,
          gender: userInfo.sex,
          content: this.newMessage
        };
		this.newMessage = "";
        client.send("/app/chat", {}, JSON.stringify(json));
        // 发送消息后执行滚动逻辑
        this.$nextTick(() => this.scrollToBottomIfNeeded());
		
		// 发送消息后获取输入框焦点
		setTimeout(()=>{
			this.focusInput();
		},300);
		
      }
    },
    getGenderImage(gender) {
      if (gender === "男") {
        return "https://img.icons8.com/color/48/000000/male.png";
      } else if (gender === "女") {
        return "https://img.icons8.com/color/48/000000/female.png";
      }
      return "";
    },
    // 滚动控制方法
    scrollToBottomIfNeeded() {
      // 获取原生DOM元素（针对uni-app的特殊处理）
      const container = this.$refs.messagesContainer?.$el || this.$refs.messagesContainer;
      if (!container) return;

      const scrollHeight = container.scrollHeight; // 内容总高度
      const clientHeight = container.clientHeight; // 可视区域高度
      const scrollTop = container.scrollTop; // 当前滚动位置
      const distanceFromBottom = scrollHeight - scrollTop - clientHeight; // 距离底部的距离

      console.log("滚动参数", { scrollHeight, scrollTop, clientHeight, distanceFromBottom });

      // 如果距离底部小于阈值，自动滚动到底部
      if (distanceFromBottom <= this.scrollThreshold) {
        console.log("触发自动滚动");
        container.scrollTop = scrollHeight;
      }
    }
  }
};
</script>





<style scoped>
/* 原有样式保持不变 */
.mes-box {
  width: 220px;
  height: 260px;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.5); /* 更暗黑的背景色 */
  color: #fff;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  position: relative;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE 和 Edge */
  scrollbar-width: none; /* Firefox */
}

/* 隐藏 Chrome、Safari 和 Opera 的滚动条 */
.messages-container::-webkit-scrollbar {
  display: none;
}

.message-item {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.self-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  margin: 0 6px;
}

.message-content {
  max-width: 70%;
}

.user-info {
  display: flex;
  align-items: center;
  font-size: 9px;
  color: #ccc;
}

.self-user-info {
  justify-content: flex-end;
}

.nickname {
  font-weight: bold;
  margin-right: 4px;
  /* 让昵称不影响气泡宽度 */
  word-break: break-all; 
}

.level {
  margin-right: 4px;
}

.gender-image {
  width: 12px;
  height: 12px;
  margin-left: 4px;
}

.chat-bubble {
  background-color: rgba(52, 152, 219, 0.8); /* 半透明背景色 */
  color: white;
  padding: 4px 8px;
  border-radius: 6px;
  position: relative;
  margin-top: 2px;
  font-size: 10px;
  word-break: break-word; /* 添加此样式让中英文正常换行 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
}

.self-message .chat-bubble {
  background-color: rgba(46, 204, 113, 0.8); /* 半透明背景色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
}

.input-container {
  display: flex;
  margin-top: 4px;
}

.message-input {
  flex: 1;
  padding: 2px 4px;
  border: none;
  border-radius: 3px;
  margin-right: 4px;
  font-size: 10px;
}

.send-button {
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 2px 8px;
  font-size: 10px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #2980b9;
}
</style>    